<?php namespace App\Http\Controllers;

use App\Admin;
use App\Answers;
use App\Banner;
use App\Building;
use App\BuildingCompany;
use App\BuildingInfos;
use App\BuildingProperty;
use App\BuildingPublicity;
use App\BuildingPartyBranch;

use App\BuildingRecruit;

use App\Classify;
use App\Content;
use App\DakaContent;
use App\Http\Services\FileManager;
use App\News;
use App\Orders;
use App\Page;
use App\Plan;
use App\PlanJoin;
use App\Profession;
use App\Questions;
use App\QuestionsAnswers;
use App\QuestionsPackage;
use App\RedInfo;
use App\RedInfoImgs;
use App\ShopInfo;
use App\SmallDevices;
use App\SmallVideo;
use App\SynchRecord;
use App\SysFeedback;
use App\User;
use App\UserDevice;
use App\Userinfo;
use App\UserRead;
use App\VideoData;
use App\VideoModel;
use App\Vip;
use App\VipInfo;
use App\VisitLog;
use Illuminate\Contracts\Auth\Guard;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;

class AdminController extends Controller
{
    public function login(){
        return view('admin.login');
    }

    public function vipList(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $ty = date('Y', time());
        $tm = date('m', time());
        $td = date('d', time());
        $todayStartTime = mktime(8,0,0,$tm,$td,$ty);
        $todayEndTime   = mktime(7,59,59,$tm,date("d")+1,$ty);

        $keyword   = !is_null($request->get('keyword')) ? $request->get('keyword') : "";
        $startTime = !is_null($request->get('start_time')) ? $request->get('start_time') : "";
        $endTime   = !is_null($request->get("end_time")) ? $request->get("end_time") : "";
        $city      = !is_null($request->get('city')) ? $request->get('city') : "";
        $province  = !is_null($request->get('province')) ? $request->get('province') : "";

        $ids = [];
        $vips = [];
        if(!is_null($keyword) && $keyword != ""){
            $ids = Vip::where("phone","like","%".$keyword."%")->pluck("id")->toArray();

            $theIds = VipInfo::where("nickname","like","%".$keyword."%")->orWhere("realname","like","%".$keyword."%")->pluck("vip_id")->toArray();
            if(count($theIds) > 0){
                foreach ($theIds as $theId){
                    if(!in_array($theId,$ids)){
                        array_push($ids,$theId);
                    }
                }
            }

            $vips = Vip::whereIn("id",$ids)->orderBy("created_at","desc")->paginate(50);
        }else if(!is_null($startTime) || !is_null($city)){
            if(is_null($endTime) && $endTime != ""){
                $endTime = date("Y-m-d H:i:s",time());
            }

            $ids = Vip::whereBetween("reg_time",[$startTime,$endTime])->pluck("id")->toArray();

            $theIds = VipInfo::where("city","like","%".$city."%")->pluck("vip_id")->toArray();
            if(count($theIds) > 0){
                foreach ($theIds as $theId){
                    if(!in_array($theId,$ids)){
                        array_push($ids,$theId);
                    }
                }
            }

            $vips = Vip::whereIn("id",$ids)->orderBy("created_at","desc")->paginate(50);
        }else{
            $vips = Vip::orderBy("created_at","desc")->paginate(50);
        }

        foreach($vips as $vip){
            /** @var User $user */
            $vipInfos = VipInfo::whereVipId($vip->id)->get();
            $vip->vip_infos = $vipInfos;
        }

        $vipCount = Vip::count();
        $todayNewVip = Vip::whereBetween("reg_time",[date("Y-m-d H:i:s",$todayStartTime),date("Y-m-d H:i:s",$todayEndTime)])->count();

        return view('admin.vip-list',[
            "vips"=>$vips,
            "vip_count"=>$vipCount,
            "today_new_vip_count"=>$todayNewVip,
            "keyword"=>$keyword,
            "start_time"=>$startTime,
            "end_time"=>$endTime,
            "province"=>$province,
            "city"=>$city
            ]);
    }

    public function userList(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $users = User::orderBy("created_at","desc")->paginate(50);

        foreach($users as $user){
            /** @var User $user */
            $user->userInfo;
        }

        return view('admin.user-list',["users"=>$users]);
    }

    public function userSet(Request $request){


        if(Auth::guard("admin")->guest())
          return response()->json(['level'=>'error','message' => '请先登录！']);

        return view('admin.user-set');

    }

    public function adminList(Request $request)
    {
        if (Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        /** @var Admin $newAdmin */
        $newAdmins = Admin::orderBy('created_at', 'desc')->paginate(10);

        return view('admin.admin-list', ['admins' => $newAdmins]);
    }

    public function adminSet(Request $request)
    {
        if (Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        return view('admin.admin-set');
    }

    public function changePwd(){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Page.login'));

        return view('admin.change-psw');
    }

    public function orderList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Page.login'));

        $newAuth = !is_null($request->get('new_auth')) ? $request->get('new_auth') : 0;
        $startTime = $request->get('start_time');
        $endTime = $request->get('end_time');

        $orders = Orders::orderBy("created",'desc')->paginate(50);

        $shopInfos = ShopInfo::all();

        $thatSynch = SynchRecord::orderBy("created_at","desc")->first();
        $allSynchRecords = SynchRecord::whereIsRead(0)->get();

        foreach ($allSynchRecords as $allSynchRecord){
            $allSynchRecord->is_read = 1;
            $allSynchRecord->read_time = date('Y-m-d H:i:s',time());
            $allSynchRecord->save();
        }

        return view('admin.order-list',[
            "orders"=>$orders,
            'shop_infos'=>$shopInfos,
            "new_auth"=>$newAuth,
            "synch"=>$thatSynch
        ]);
    }

    public function dataShow(Request $request){
        $selectTime = $request->get('select_time');

        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Page.login'));

        //获取昨天的最大时间和最小时间
        $yy = date('Y', strtotime('-1 days'));
        $ym = date('m', strtotime('-1 days'));
        $yd = date('d', strtotime('-1 days'));
        $yesterdayStartTime = mktime(0,0,0,$ym,$yd,$yy);
        $yesterdayEndTime   = mktime(23,59,59,$ym,$yd,$yy);

        //获取当天的最大时间和最小时间
        $ty = date('Y', time());
        $tm = date('m', time());
        $td = date('d', time());
        $todayStartTime = mktime(0,0,0,$tm,$td,$ty);
        $todayEndTime   = mktime(23,59,59,$tm,$td,$ty);

        //获取本月的第一天和最后一天
        $beginMonth = date('Y-m-01 00:00:00', strtotime(date("Y-m-d")));
        $endMonth   = date('Y-m-d 23:59:59', strtotime("$beginMonth +1 month -1 day"));

        //用户数据统计
        $todayVipCount     = Vip::whereBetween('reg_time',[date('Y-m-d H:i:s',$todayStartTime),date('Y-m-d H:i:s',$todayEndTime)])->count(); //今日新增用户
        $yesterdayVipCount = Vip::whereBetween('reg_time',[date('Y-m-d H:i:s',$yesterdayStartTime),date('Y-m-d H:i:s',$yesterdayEndTime)])->count(); //昨日新增用户
        $theMonthVipCount  = Vip::whereBetween('reg_time',[$beginMonth,$endMonth])->count();
        $allVipCount       = Vip::count();

        //平台收入统计
        $todayOrderCount     = Orders::whereNotNull("pay_time")->whereBetween('created',[date('Y-m-d H:i:s',$todayStartTime),date('Y-m-d H:i:s',$todayEndTime)])->count(); //今日新增订单数
        $yesterdayOrderCount = Orders::whereNotNull("pay_time")->whereBetween('created',[date('Y-m-d H:i:s',$yesterdayStartTime),date('Y-m-d H:i:s',$yesterdayEndTime)])->count(); //昨日新增用户
        $theMonthOrderCount  = Orders::whereNotNull("pay_time")->whereBetween('created',[$beginMonth,$endMonth])->count();
        $allOrderCount       = Orders::whereNotNull("pay_time")->count();

        $todayOrderSum     = Orders::whereNotNull("pay_time")->whereBetween('created',[date('Y-m-d H:i:s',$todayStartTime),date('Y-m-d H:i:s',$todayEndTime)])->sum('total_fee'); //今日新增用户
        $yesterdayOrderSum = Orders::whereNotNull("pay_time")->whereBetween('created',[date('Y-m-d H:i:s',$yesterdayStartTime),date('Y-m-d H:i:s',$yesterdayEndTime)])->sum('total_fee'); //昨日新增用户
        $theMonthOrderSum  = Orders::whereNotNull("pay_time")->whereBetween('created',[$beginMonth,$endMonth])->sum('total_fee');
        $allAmountSum      = Orders::whereNotNull("pay_time")->sum('total_fee');

        //24小时订单统计
        $selectDate = null;
        if(is_null($selectTime) || $selectTime == ''){
            $selectDate = date('Y-m-d',time());
        }else{
            $selectDate = $selectTime;
        }

        $hoursOrderNum = array();
        for($i=0;$i<=24;$i++){
            $startTime = strtotime($selectDate) + ($i * 3600);
            $endTime   = strtotime($selectDate) + (($i+1) * 3600) -1;
            $theHourCount = Orders::whereBetween('created',[date('Y-m-d H:i:s',$startTime),date('Y-m-d H:i:s',$endTime)])->count();
            array_push($hoursOrderNum,$theHourCount);
        }

        return view('admin.data-show',[
            "today_vip_count" => $todayVipCount,
            "yesterday_vip_count" => $yesterdayVipCount,
            "the_month_vip_count" => $theMonthVipCount,
            "all_vip_count" => $allVipCount,
            "today_order_count" => $todayOrderCount,
            "yesterday_order_count" => $yesterdayOrderCount,
            "the_month_order_count" => $theMonthOrderCount,
            "all_order_count" => $allOrderCount,
            "today_order_sum" => $todayOrderSum,
            "yesterday_order_sum" => $yesterdayOrderSum,
            "the_month_order_sum" => $theMonthOrderSum,
            "all_amount_sum" => $allAmountSum,
            "hour_nums" => $hoursOrderNum,
            "select_time"=>$selectTime
        ]);
    }
}